package com.bdqn.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.mapper.RoleMapper;
import com.bdqn.pojo.Right;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.repository.RightRepository;
import com.bdqn.repository.RoleRepository;
import com.bdqn.service.RoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色Service实现
 *
 * @author LILIBO
 * @since 2024/09/07
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleRepository roleRepository;
    @Resource
    private RightRepository rightRepository;

    /**
     * 获取所有角色信息
     *
     * @return
     */
    @Override
    @Cacheable(value = "role", key = "'all'", unless = "#result==null")
    public List<Role> findAll() {
        return super.list();
    }

    @Override
    public List<Role> findAllRoles() {
        return roleRepository.findAll();
    }

    @Override
    public Role saveRole(Role role) {
        return roleRepository.save(role);
    }

    @Override
    public void deleteRoleById(Long roleId) {
        roleRepository.deleteById(roleId);
    }

    @Override
    public void deleteRole(Role role) {
        roleRepository.delete(role);
    }

    @Override
    public Role getRole(Long roleId) {
        return roleRepository.findById(roleId).get();
    }

    @Override
    public Page<Role> findRole(String roleName, Pageable pageable) {
        return roleRepository.findRolesByRoleNameLike("%"+roleName+"%",pageable);
    }

    @Override
    public List<Right> findRightsByRole(Role role) {
        return rightRepository.findRightsByRolesOrderByRightCode(role);
    }

    @Override
    public List<Right> findAllRights() {
        return rightRepository.findAll();
    }

    @Override
    public Role findRoleByUsers(User user) {
        return roleRepository.findRoleByUsers(user);
    }

    public Map<String,String> loadFilterChainDefinitions(){
        Map<String,String> filterChainDefinitionMap=new LinkedHashMap<>();
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");

        // API接口请求授权
        filterChainDefinitionMap.put("/api/**", "anon");

        // 登录退出页面设置
        filterChainDefinitionMap.put("/login", "anon"); // 点击登录按钮时放行
        filterChainDefinitionMap.put("/logout", "logout"); // 点击退出按钮时放行

        // 动态授权
        List<Right> rights = findAllRights();
        for (Right right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightCode() + "]");
            }
        }

        // 配置认证访问：其他资源(URL)必须认证通过才能访问
        filterChainDefinitionMap.put("/**", "authc"); // 必须放在过滤器链的最后面

        return filterChainDefinitionMap;
    }

    public void reloadFilterChainDefinitions(){
        try{
            HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext=request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter= (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("shiroFilterFactory");
            synchronized (shiroFilter){
                PathMatchingFilterChainResolver filterChainResolver= (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager= (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                manager.getFilterChains().clear();
                Map<String,String> chains=loadFilterChainDefinitions();
                for (Map.Entry<String,String> entry:chains.entrySet()){
                    String url=entry.getKey();
                    String chainDefinition=entry.getValue().trim().replace(" ","");
                    manager.createChain(url,chainDefinition);
                }
            }
            System.out.println("更新权限成功！！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}




